package com.niit.maxandmin;

import org.apache.commons.math3.analysis.function.Max;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * Date:2024/11/1
 * Author：Ys
 * Description:
 *    Mapper的输出 等于 Reducer的输入
 */
public class MaxAndMinReducer extends Reducer<MaxAndMinValue, NullWritable,NullWritable,MaxAndMinValue> {

    private long min;
    private long max;
    private int total;

    @Override
    protected void setup(Reducer<MaxAndMinValue, NullWritable, NullWritable, MaxAndMinValue>.Context context) throws IOException, InterruptedException {
        min = Long.MIN_VALUE;
        max = Long.MAX_VALUE;
        total = 0;
    }

    @Override
    protected void reduce(MaxAndMinValue key, Iterable<NullWritable> values, Reducer<MaxAndMinValue, NullWritable, NullWritable, MaxAndMinValue>.Context context) throws IOException, InterruptedException {
                          // MaxAndMinValue 是Mapper输出给Reducer阶段的数据，里面包含了我们上一步（Mapper）结果  min:99 max:1 total:3

        if(key.getMin().get() < max){
            max = key.getMin().get();
        }

        if(key.getMax().get() > min){
            min = key.getMax().get();
        }

        total += key.getTotal().get();

    }

    @Override
    protected void cleanup(Reducer<MaxAndMinValue, NullWritable, NullWritable, MaxAndMinValue>.Context context) throws IOException, InterruptedException {
        MaxAndMinValue  maxAndMinValue = new MaxAndMinValue(min,max,total);
        context.write(NullWritable.get(),maxAndMinValue);

    }
}
